package com.wonderful.mall.ware.service.impl;


import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import com.wonderful.common.exception.NoStockException;
import com.wonderful.common.to.mq.OrderTo;
import com.wonderful.common.to.mq.StockDetailTo;
import com.wonderful.common.to.mq.StockLockedTo;
import com.wonderful.common.utils.PageUtils;
import com.wonderful.common.utils.Query;

import com.wonderful.common.utils.R;
import com.wonderful.mall.ware.dao.WareSkuDao;
import com.wonderful.mall.ware.entity.WareOrderTaskDetailEntity;
import com.wonderful.mall.ware.entity.WareOrderTaskEntity;
import com.wonderful.mall.ware.entity.WareSkuEntity;
import com.wonderful.mall.ware.feign.OrderFeignService;
import com.wonderful.mall.ware.service.WareOrderTaskDetailService;
import com.wonderful.mall.ware.service.WareOrderTaskService;
import com.wonderful.mall.ware.service.WareSkuService;
import com.wonderful.mall.ware.vo.OrderItemVo;
import com.wonderful.mall.ware.vo.OrderVo;
import com.wonderful.mall.ware.vo.SkuHasStockVo;
import com.wonderful.mall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Resource
    WareSkuDao wareSkuDao;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    WareOrderTaskService wareOrderTaskService;
    @Resource
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Resource
    OrderFeignService feignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isNullOrEmpty(wareId)) {
            wrapper.eq("ware_id", wareId);
        }

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isNullOrEmpty(skuId)) {
            wrapper.eq("sku_id", skuId);
        }


        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, String skuName, Integer skuNum) {
        WareSkuEntity wareSkuEntity = this.baseMapper.selectOne(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntity == null) {
            //新增
            wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setStock(skuNum);
        } else {
            wareSkuEntity.setStock(wareSkuEntity.getStock() + skuNum);
        }
        wareSkuEntity.setSkuName(skuName);
        wareSkuEntity.setWareId(wareId);
        wareSkuEntity.setSkuId(skuId);

        this.saveOrUpdate(wareSkuEntity);
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        return skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            //查询当前sku总库存量
//            select sum(stock-stock_locked) from wms_ware_sku where sku_id = 1;
            QueryWrapper<WareSkuEntity> sku_id = new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId);
            WareSkuEntity wareSkuEntity = baseMapper.selectOne(sku_id);
            if (wareSkuEntity != null) {
                long count = wareSkuEntity.getStock() - wareSkuEntity.getStockLocked();
                vo.setSkuId(skuId);
                vo.setHasStock(count > 0);
            }
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 为某个订单锁定库存
     * <p></p>
     * 库存解锁
     * 1、下单成功，订单过期没有支付
     * 2、用户手动取消
     * 3、业务调用失败导致订单回滚
     */
    @Override
    @Transactional(rollbackFor = NoStockException.class)
    public Boolean orderLockStock(WareSkuLockVo vo) {
        //保存库存工作单
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);

        List<OrderItemVo> locks = vo.getLocks();
        List<skuWareHasStock> collect = locks.stream().map(item -> {
            skuWareHasStock stock = new skuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            stock.setNum(item.getCount());
            return stock;
        }).collect(Collectors.toList());

        for (skuWareHasStock stock : collect) {
            boolean skuStoked = false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            Integer num = stock.getNum();
            if (wareIds == null || wareIds.size() == 0) {
                throw new NoStockException(skuId);
            }
            //每一个商品都锁定成功，将当前商品锁定了几件的工作单记录发送给mq
            //锁定失败，前面保存的工作单信息回滚。已经发送出去的消息，即使要解锁记录，由于去数据库查不到id，所以不用解锁
            for (Long wareId : wareIds) {
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, num);
                if (count == 1) {
                    skuStoked = true;
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity(null, skuId, "", num, taskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(detailEntity);
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    //防止回滚以后找不到数据
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(detailEntity, stockDetailTo);
                    lockedTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.lock.stock", lockedTo);
                    break;
                }
            }
            if (!skuStoked) {
                throw new NoStockException(skuId);
            }
        }
        return null;
    }

    @Override
    public void unlockStock(StockLockedTo to) {

        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        //TODO 远程调用订单服务查询订单状态
        //解锁
        //查询数据库关于这个订单的所订购库存信息
        //有：锁定库存成功
        //      查询订单：
        //              没有这个订单，解锁库存
        //              有这个订单，查询订单状态
        //                          已取消：解锁库存
        //                          未取消：无需解锁
        //无：锁定库存失败，无需解锁
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(detailId);
        if (detailEntity != null) {
            //解锁
            Long id = to.getId();//库存工作单的id
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R r = feignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                //远程调用成功
                OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {
                });
                if (orderVo == null || orderVo.getStatus() == 4) {
                    if (detailEntity.getLockStatus() == 1) {
                        //订单被被取消，解锁库存
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                throw new RuntimeException("远程调用失败");
            }
        }
    }

    @Override
    @Transactional
    public void unlockStock(OrderTo to) {
        String orderSn = to.getOrderSn();
        //查询库存解锁状态
        WareOrderTaskEntity task = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long taskId = task.getId();
        //按照工作单找到所有没有解锁的库存
        List<WareOrderTaskDetailEntity> entities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", taskId).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : entities) {
            unLockStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }
    }

    private void unLockStock(Long skuId, Long wareId, Integer num, Long detailId) {
        wareSkuDao.unlockStock(skuId, wareId, num);
        WareOrderTaskDetailEntity taskEntity = new WareOrderTaskDetailEntity();
        taskEntity.setId(detailId);
        taskEntity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(taskEntity);
    }

    @Data
    static class skuWareHasStock {
        private Long skuId;
        private List<Long> wareId;
        private Integer num;
    }

}